package com.tsl.prevention.modules.wechat;

import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.apache.tomcat.util.codec.binary.Base64;
import com.qcloud.cos.*;
import com.qcloud.cos.auth.*;
import com.qcloud.cos.exception.*;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.tsl.prevention.util.HttpRequest;
import com.tsl.prevention.util.Result;
import com.tsl.prevention.util.StringUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.InputStream;
import java.security.spec.AlgorithmParameterSpec;
import java.util.UUID;

/**
 * @Author wang.hongyu
 * @Version V1.02021/03/25
 **/
@RestController
@RequestMapping("/wechat")
public class WechatController {
    private static final String SECRET_ID = "AKIDpN0LSc5O1ffU6nHolAXgggWO02GHCa7T";
    private static final String SECRET_KEY = "ELBoAExA8p7C5wXMIySiUzSjtnUxBMHw";
    private static final String BUCKETNAME = "demo-1305283561";
    private static final String REGIONID = "ap-nanjing";
    private static final String KEY="C:\\Users\\My\\Desktop\\image\\1.jpg";
    private String appId = "wxd3b929046b12df6e";
    private String appSecret = "dfb1a458381143c501f421ef0f50c872";
    /**
     * 初始化CosClient相关配置， appid、accessKey、secretKey、region
     * @return
     */
    public static COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        //String bucketName = BUCKETNAME;
        return cosClient;
    }

    /**
     * 上传文件
     * @return
     * //绝对路径和相对路径都OK
     */
    public static String uploadFile(File localFile) {
        //自己更改本地上传文件
//        File localFile = new File("/Users/ouhiroshisakai/Desktop/QQ20210110-191136@2x.png");
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, localFile.getName(), localFile);

        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia),一般为标准的
        putObjectRequest.setStorageClass(StorageClass.Standard);

        COSClient cc = getCosClient();
        try {
            PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String etag = putObjectResult.getETag();
            System.out.println(etag);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cc.shutdown();
        return null;
    }

//    public static void main(String[] args) {
//        getCosClient();
//        uploadFile();
//    }

    @PostMapping("/upload")
    public Result upLoad(@RequestBody MultipartFile file) throws Exception {
        getCosClient();
        File file1 = StringUtil.multipartFileToFile(file);
        uploadFile(file1);
        return Result.create("https://demo-1305283561.cos.ap-nanjing.myqcloud.com/"+file1.getName());
    }

    /**
     * 解密用户手机号
     * @param keyStr sessionkey
     * @param ivStr  ivData
     * @param encDataStr 带解密数据
     * @return
     * @throws Exception
     * @date 2019年05月08日
     */
    @GetMapping("/decrypt")
    public  String decrypt( String code ,String ivStr, String encDataStr)throws Exception {
        encDataStr = encDataStr.replaceAll(" ","+");
        byte[] encData = Base64.decodeBase64(encDataStr);
        ivStr = ivStr.replaceAll(" ","+");
        byte[] iv =Base64.decodeBase64(ivStr);
//        byte[] key = Base64.decode(keyStr);
        //获取session_key
        String openId = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" +appSecret+ "&js_code=" + code + "&grant_type=authorization_code", code);
        JSONObject jsonObject = JSONObject.parseObject(openId);
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] session_keys = Base64.decodeBase64(jsonObject.getString("session_key"));
        SecretKeySpec keySpec = new SecretKeySpec(session_keys ,"AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return new String(cipher.doFinal(encData),"UTF-8");
    }
}
